import { defineStore } from "pinia";
import { loginApi, getUserInfo, logout } from "@/api/user.ts";
import { navigate } from "@/utils/utils.ts";
type loginData = {
  code: string;
};
export const useUserStore = defineStore("userStore", {
  state: () => ({
    userInfo: {},
    accessToken: "",
  }),
  actions: {
    login(data: loginData) {
      return new Promise(async (resolve) => {
        let res = await loginApi(data);
        this.accessToken = res.token;
        this.userInfo = await getUserInfo();
        resolve(this.userInfo);
      });
    },
    async userLogout() {
      let r = await logout();
      this.reset();
      uni.showToast({
        title: "退出成功",
        success() {
          setTimeout(() => {
            navigate("/pages/index/index", "s");
          }, 2000);
        },
      });
    },
    reset() {
      this.userInfo = {};
      this.accessToken = "";
    },
  },
  persist: {
    storage: {
      getItem: uni.getStorageSync,
      setItem: uni.setStorageSync,
    },
  },
});
